import axios from 'axios'
import bridge from '@/utils/bridge.js'
import qs from './querystring' // 不用qs库的原因见./querystring
import type {
  AxiosInstance,
  AxiosRequestConfig,
  InternalAxiosRequestConfig,
  AxiosResponse
} from 'axios'
import { getToken } from '@/utils/auth' //
import { tansParams } from '@/utils/tools'

// 扩展 AxiosRequestConfig 类型，添加自定义属性 isUpload
declare module 'axios' {
  interface AxiosRequestConfig {
    isUpload?: boolean // 自定义属性
  }
}

// 创建axios实例
const service: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_BASEURL, // 在.env文件中配置
  timeout: 100000,
  headers: { 'Content-Type': 'application/json;charset=utf-8' }
})

// 请求拦截器
service.interceptors.request.use(
  async (config: InternalAxiosRequestConfig) => {
    // 携带token
    const token = await getToken()
    console.log('token', token)
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    // config.headers.Authorization = `Bearer ${qs.parse(location.href.split('?')[1]).code}`
    if (config.isUpload) {
      config.headers['Content-Type'] = 'multipart/form-data'
    }
    return config
  },
  (error: any) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const res = response.data
    // 业务状态码判断
    if (res.code === 401) {
      // token失效，跳转到登录页
      showToast('登录过期，请先登录')
      bridge.navigateBackTo({
        value: 'login'
      })
    } else if (res.code !== 200 && res.code !== 0) {
      showToast(res.msg || '请求失败')
      // 将后端响应对象直接抛出，便于业务侧读取 msg
      return Promise.reject(res)
    }
    return res
  },
  (error: any) => {
    console.log(error)
    // HTTP状态码处理
    let message = error.message
    if (error.response?.status) {
      switch (error.response.status) {
        case 401:
          message = '身份认证失败，请重新登录'
          // 这里可以跳转到登录页
          break
        case 404:
          message = '资源不存在'
          break
        case 500:
          message = '服务器内部错误'
          break
      }
    }
    showToast(message)
    return Promise.reject(error)
  }
)

// 封装通用请求方法
interface Response<T> {
  code: number
  data: T
  message: string
}

export const http = {
  get<T = any>(url: string, config?: AxiosRequestConfig): Promise<Response<T>> {
    if (tansParams(config)) {
      url = `${url}?${tansParams(config)}`
    }

    return service.get(url, config)
  },

  post<T = any>(url: string, data?: object, config?: AxiosRequestConfig): Promise<Response<T>> {
    return service.post(url, data, config)
  }
}

export default service
